Skip to main content

Reuse objects rather than recreate

Example A

var i,a,b,len;
a = {x:0,y:0}
function test(){ // return object created each call
return {x:0,y:0}; }
function test1(a){ // return object supplied a.x=0;
a.y=0;
return a; }
for(i = 0; i < 100; i ++){ // Loop A b = test();
}
for(i = 0; i < 100; i ++){ // Loop B b = test1(a);
}

Loop B is 4 (400%) times faster than Loop A

It is very inefficient to create a new object in performance code. Loop A calls function test() which returns a new object every call. The created object is discarded every iteration, Loop B calls test1() that requires the object returns to be supplied. It thus uses the same object and avoids allocation of a new object, and excessive GC hits. (GC were not included in the performance test)

Example B

var i,a,b,len;
a = {x:0,y:0} function test2(a){
return {x : a.x * 10,y : a.x * 10}; }
function test3(a){ a.x= a.x * 10; a.y= a.y * 10;
return a; }
for(i = 0; i < 100; i++){
b = test2({x : 10, y : 10});
}
for(i = 0; i < 100; i++){ // Loop B
a.x = 10;
a.y = 10;
b = test3(a);
}

Loop B is 5 (500%) times faster than loop A